// write-word.js - 写单词组件逻辑
Component({
  properties: {
    currentWord: {
      type: Object,
      value: {}
    },
    pronunciationType: {
      type: String,
      value: "american"
    },
    playbackSpeed: {
      type: Number,
      value: 1.0
    },
    show: {
      type: Boolean,
      value: false,
      observer: "_onShowChange"
    }
  },
  
  data: {
    writtenWord: '',
    showWriteResult: false,
    writeResultText: '',
    audioContext: null,
    isPlaying: false,
    currentAudioUrl: ''
  },
  
  methods: {
    _onShowChange: function(newVal) {
      if (newVal) {
        this.setData({
          writtenWord: '',
          showWriteResult: false,
          writeResultText: ''
        });
      }
    },
    
    playWritePronunciation: function() {
      const speed = this.data.playbackSpeed;
      const type = this.properties.pronunciationType;
      const currentWord = this.properties.currentWord;

      if (!currentWord || !currentWord.english) {
        wx.showToast({
          title: '当前没有单词可播放',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 如果正在播放，先停止当前播放
      if (this.data.isPlaying && this.data.audioContext) {
        this.stopPronunciation();
      }

      // 获取音频URL（这里使用模拟的音频URL）
      const audioUrl = this.getAudioUrl(currentWord.english, type);

      if (!audioUrl) {
        wx.showToast({
          title: '音频资源不存在',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 初始化音频上下文
      if (!this.data.audioContext) {
        this.data.audioContext = wx.createInnerAudioContext();
        this.setData({
          audioContext: this.data.audioContext
        });

        // 设置音频上下文事件监听
        this.data.audioContext.onPlay(() => {
          console.log('音频开始播放');
          this.setData({
            isPlaying: true
          });
        });

        this.data.audioContext.onEnded(() => {
          console.log('音频播放结束');
          this.setData({
            isPlaying: false
          });
        });

        this.data.audioContext.onError((error) => {
          console.error('音频播放错误:', error);
          this.setData({
            isPlaying: false
          });
          wx.showToast({
            title: '播放失败',
            icon: 'none',
            duration: 2000
          });
        });

        this.data.audioContext.onStop(() => {
          console.log('音频播放停止');
          this.setData({
            isPlaying: false
          });
        });
      }

      // 确保audioContext存在后再设置属性和播放
      if (!this.data.audioContext) {
        wx.showToast({
          title: '音频初始化失败',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 设置音频属性
      this.data.audioContext.src = audioUrl;
      this.data.audioContext.playbackRate = speed; // 设置播放倍速
      this.data.audioContext.volume = 1.0; // 设置音量

      // 开始播放（使用更安全的Promise处理）
      try {
        const playPromise = this.data.audioContext.play();

        // 检查是否返回Promise
        if (playPromise && typeof playPromise.then === 'function') {
          playPromise.then(() => {
            this.setData({
              isPlaying: true,
              currentAudioUrl: audioUrl
            });
            console.log(`开始播放: ${currentWord.english} (${type}, ${speed}x)`);
          }).catch((error) => {
            console.error('播放失败:', error);
            this.setData({
              isPlaying: false
            });
            wx.showToast({
              title: '播放失败',
              icon: 'none',
              duration: 2000
            });
          });
        } else {
          // 如果不是Promise，直接设置状态
          this.setData({
            isPlaying: true,
            currentAudioUrl: audioUrl
          });
          console.log(`开始播放: ${currentWord.english} (${type}, ${speed}x)`);
        }
      } catch (error) {
        console.error('播放调用失败:', error);
        this.setData({
          isPlaying: false
        });
        wx.showToast({
          title: '播放失败',
          icon: 'none',
          duration: 2000
        });
      }
    },
    
    stopPronunciation: function() {
      if (this.data.audioContext && this.data.isPlaying) {
        this.data.audioContext.stop();
        this.setData({
          isPlaying: false
        });
        console.log('停止播放音频');
      }
    },
    
    getAudioUrl: function(word, type) {
      // 这里使用模拟的音频URL，实际项目中应该从服务器获取
      // 为了简化，返回null表示没有音频
      return null;
    },
    
    onWrittenWordChange: function(e) {
      // 用户输入单词变化
      this.setData({
        writtenWord: e.detail.value
      });
    },
    
    checkWrittenWord: function() {
      // 检查书写答案
      const userInput = this.data.writtenWord.trim().toLowerCase();
      const correctWord = this.properties.currentWord.english.toLowerCase();
      
      if (userInput === correctWord) {
        this.setData({
          showWriteResult: true,
          writeResultText: '回答正确！'
        });
        // 可以自动标记为已学
      } else {
        this.setData({
          showWriteResult: true,
          writeResultText: `回答错误，正确答案是：${correctWord}`
        });
      }
    },
    
    exitWriteMode: function() {
      // 停止音频播放
      if (this.data.audioContext) {
        this.stopPronunciation();
      }
      
      // 触发退出事件
      this.triggerEvent('exit', {});
    }
  },
  
  detached: function() {
    // 组件卸载时清理音频上下文
    if (this.data.audioContext) {
      this.data.audioContext.destroy();
      this.setData({
        audioContext: null
      });
    }
  }
});